<template>
  <el-row>
    <el-col :span="24">
      <div class="box">
        <div class="box-header">
          <el-col :span="2">
            <h3 class="box-title" style="line-height: 40px;float: left;">
              培训信息
            </h3>
          </el-col>
          <el-col :span="2">
            <!-- <div class="button-group pull-left"> -->
            <el-button
              class="btn-link-large add-btn"
              @click="seeAdd = true"
              v-if="operating"
            >
              <i class="el-icon-plus el-icon--right"> 发 布</i>
            </el-button>
            <!-- </div> -->
          </el-col>
          <el-col :span="18">
            <!-- 搜索 -->
            <div style="line-height: 40px;float: left; margin-left: 10px;">
              <el-form :model="searchData">
                <el-input
                  v-model="searchData.issue"
                  placeholder="培训期数"
                  clearable
                  style="width: 20%; margin:auto 5px;"
                ></el-input>
                <el-input
                  v-model="searchData.company"
                  placeholder="主办单位"
                  clearable
                  style="width: 20%; margin:auto 5px;"
                ></el-input>
                <el-input
                  v-model="searchData.traindata_name"
                  placeholder="培训主题关键字"
                  show-word-limit
                  clearable
                  style="width: 20%;margin:auto 5px;"
                ></el-input>
                <el-date-picker
                  style="width: 33%"
                  v-model="time"
                  value-format="yyyy-MM-dd"
                  type="daterange"
                  align="right"
                  unlink-panels
                  :picker-options="pickerOptions"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                ></el-date-picker>
              </el-form>
            </div>
          </el-col>
          <el-col :span="2">
            <!-- <div style="line-height: 40px;float: left;"> -->
            <el-button class="btn-link-large add-btn" @click="Search()">
              <i class="el-icon-search el-icon--right"> 搜 索</i>
            </el-button>
            <!-- </div> -->
          </el-col>
        </div>
        <!-- 一级菜单 -->
        <div class="box-body">
          <el-table
            :data="tableData1"
            v-loading="loading"
            stripe
            style="width: 100%"
            @row-click="clickRow"
          >
            <el-table-column
              prop="id"
              label="ID"
              width="60"
              sortable
            ></el-table-column>
            <el-table-column
              prop="start_time"
              label="开始时间"
              sortable
            ></el-table-column>
            <el-table-column
              prop="end_time"
              label="结束时间"
              sortable
            ></el-table-column>
            <el-table-column
              prop="issue"
              label="培训期数"
              sortable
            ></el-table-column>
            <el-table-column
              prop="traindata_name"
              label="培训主题"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              prop="company"
              label="主办单位"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              prop="traindata_address"
              label="培训地点"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column prop="level" label="培训级别"></el-table-column>
            <el-table-column prop="status" label="培训状态">
              <template scope="scope">
                <!-- <el-tag type="warning" v-if="scope.row.status == 0" close-transition>正在审核</el-tag> -->
                <el-tag
                  type="success"
                  v-if="scope.row.status == 1"
                  close-transition
                  width="80"
                  >培训中</el-tag
                >
                <el-tag
                  type="danger"
                  v-if="scope.row.status == 2"
                  close-transition
                  >已结束</el-tag
                >
              </template>
            </el-table-column>
            <el-table-column label="操作" v-if="operating" width="350">
              <template slot-scope="scope">
                <el-button
                  v-popover:popover5
                  style="background: #367fa9;"
                  size="small"
                  type="primary"
                  icon="el-icon-video-play"
                  :disabled="scope.row.status == 2"
                  @click.stop="stopExe(scope.row)"
                  >结束</el-button
                >
                <el-button
                  v-popover:popover5
                  size="small"
                  type="primary"
                  icon="el-icon-edit"
                  @click.stop="Edit(scope.row)"
                  >修改</el-button
                >
                <el-button
                  v-popover:popover5
                  size="small"
                  type="danger"
                  icon="el-icon-delete"
                  @click.stop="confirmDelete(scope.row)"
                  >删除</el-button
                >
                 <el-button
                  v-popover:popover5
                  size="small"
                  type="success"
                  icon="el-icon-download"
                  @click.stop="print(scope.row)"
                  >打印</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            layout="prev, pager, next"
            :page-count="total"
            style="float: right;"
          ></el-pagination>
        </div>
      </div>
    </el-col>
    <!-- 新增培训信息 -->
    <el-dialog title="新增培训信息" :visible.sync="seeAdd" width="20%" center>
      <el-form :model="trainData">
        <el-date-picker
          style="width: 100%;"
          v-model="trainData.start_time"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="培训开始时间"
        ></el-date-picker>
        <el-date-picker
          style="width: 100%;margin:10px auto;"
          v-model="trainData.end_time"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="培训结束时间"
        ></el-date-picker>
        <el-input
          v-model="trainData.issue"
          placeholder="培训期数"
          clearable
        ></el-input>
        <el-input
          v-model="trainData.company"
          placeholder="主办单位"
          clearable
          style="margin:10px auto;"
        ></el-input>
        <el-input
          v-model="trainData.traindata_address"
          placeholder="培训地点"
          clearable
        ></el-input>
        <el-select
          v-model="trainData.level"
          placeholder="请选择"
          style="width: 100%;margin:10px auto;"
        >
          <el-option
            v-for="item in levels"
            :key="item.value"
            :label="item.label"
            :value="item.label"
          >
          </el-option>
        </el-select>
        <el-input
          style="width: 100%;"
          type="textarea"
          :autosize="{ minRows: 3, maxRows: 5 }"
          v-model="trainData.traindata_name"
          placeholder="培训主题"
          maxlength="50"
          show-word-limit
          clearable
        ></el-input>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="seeAdd = false">取 消</el-button>
        <el-button type="primary" @click="addTrain()">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 修改培训信息 -->
    <el-dialog title="修改培训信息" :visible.sync="editInfo" width="20%" center>
      <el-form :model="editData">
        <el-date-picker
          style="width: 100%;"
          v-model="editData.start_time"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="培训开始时间"
        ></el-date-picker>
        <el-date-picker
          style="width: 100%;margin:10px auto;"
          v-model="editData.end_time"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="培训结束时间"
        ></el-date-picker>
        <el-input
          v-model="editData.issue"
          placeholder="培训期数"
          clearable
        ></el-input>
        <el-input
          v-model="editData.company"
          placeholder="主办单位"
          clearable
          style="margin:10px auto;"
        ></el-input>
        <el-input
          v-model="editData.traindata_address"
          placeholder="培训地点"
          clearable
        ></el-input>
        <el-select
          v-model="editData.level"
          placeholder="请选择"
          style="width: 100%;margin:10px auto;"
        >
          <el-option
            v-for="item in levels"
            :key="item.value"
            :label="item.label"
            :value="item.label"
          >
          </el-option>
        </el-select>
        <el-input
          style="width: 100%;"
          type="textarea"
          :autosize="{ minRows: 3, maxRows: 5 }"
          v-model="editData.traindata_name"
          placeholder="培训主题"
          maxlength="50"
          show-word-limit
          clearable
        ></el-input>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editInfo = false">取 消</el-button>
        <el-button type="primary" @click="editTrain()">确 定</el-button>
      </div>
    </el-dialog>
  </el-row>
</template>

<script>
import http from './../../../assets/js/http'
export default {
  data() {
    return {
      levels: [
        {
          value: '选项1',
          label: '校级'
        },
        {
          value: '选项2',
          label: '省级'
        },
        {
          value: '选项3',
          label: '国家级'
        }
      ],
      tableData1: [],
      trainData: {}, // 新增
      editData: {}, // 编辑
      searchData: {}, // 搜索
      time: ['', ''],
      loading: true,
      seeAdd: false,
      editInfo: false,
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      currentPage: 1,
      total: 1,
      userInfo: Lockr.get('userInfo'),
      operating: true
    }
  },
  methods: {
    // 点击某一行，进入详情界面
    clickRow(row) {
      // console.log(row)
      console.log(this.tableData1)

      router.push({ name: 'sch', params: { id: row.id } })
    },
    // 点击培训信息下的页码，返回对应的数据
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage
      let data = {
        page: this.currentPage
      }
      this.GetTableData(data)
    },
    // 显示一级列表
    GetTableData(data) {
      this.loading = true
      this.apiPost('admin/Traindata/TraindataList', data).then(res => {
        this.handelResponse(res, data => {
          // console.log(res.data.data)
          this.tableData1 = res.data.data
          this.total = Math.ceil(data.total / data.per_page)
        })
        this.loading = false
      })
    },
    // 添加培训信息
    addTrain(trainData) {
      // console.log(this.trainData)
      var checkResult = this.checkList(this.trainData, [
        {
          name: 'start_time',
          reg: ['notnull']
        },
        {
          name: 'end_time',
          reg: ['notnull']
        },
        {
          name: 'company',
          reg: ['notnull']
        },
        {
          name: 'issue',
          reg: ['notnull']
        },
        {
          name: 'traindata_address',
          reg: ['notnull']
        },
        {
          name: 'level',
          reg: ['notnull']
        },
        {
          name: 'traindata_name',
          reg: ['notnull']
        }
      ])
      if (_g.j2s(checkResult) === '{}') {
        let data = this.trainData
        this.apiPost('admin/Traindata/TraindataInsert', data).then(res => {
          this.handelResponse(res, data => {
            _g.toastMsg('success', '培训信息添加成功')
            setTimeout(() => {
              this.seeAdd = false
              this.trainData = {}
              this.GetTableData()
            }, 1000)
          })
        })
      }
    },
    // 点击修改按钮，弹出修改的dialog
    Edit(item) {
      console.log(item)
      this.editInfo = true
      // this.editData = item
      /*
        （1）直接 this.editData = item ,这样的话也会让改行的信息显示在edit的dialog中。
              但是存在的问题： 就是在dialog进行信息修改的时候，会导致默认列表的对应信息也跟着改变。
              原因： post从后台取出的tableData1，通过v-for渲染，取出的一条item实际上就是tableData1[i]
                    所以修改dialog的内容，实际就是在修改tableData1
        （2）解决办法：将取出的dialog重新复制给新的对象
              a)  Object.assign() 方法用于将所有可枚举属性的值从一个或多个源对象复制到目标对象。它将返回目标对象。
                  使用方法： Object.assign({}, str)
                  博客讲解地址: https://www.jianshu.com/p/e22113e3f614
              b)  JSON.parse(JSON.stringify(str))
                  博客讲解地址：https://blog.csdn.net/weixin_34221112/article/details/88624159?utm_source=app
       */
      // var editData =  Object.assign({}, item)
      var editData = JSON.parse(JSON.stringify(item))
      this.editData = editData
      console.log(this.editData)
    },
    // 修改培训信息
    editTrain(editData) {
      console.log(this.editData)
      var checkResult = this.checkList(this.editData, [
        {
          name: 'start_time',
          reg: ['notnull']
        },
        {
          name: 'end_time',
          reg: ['notnull']
        },
        {
          name: 'company',
          reg: ['notnull']
        },
        {
          name: 'issue',
          reg: ['notnull']
        },
        {
          name: 'traindata_address',
          reg: ['notnull']
        },
        {
          name: 'level',
          reg: ['notnull']
        },
        {
          name: 'traindata_name',
          reg: ['notnull']
        }
      ])
      if (_g.j2s(checkResult) === '{}') {
        let data = this.editData
        this.apiPost('admin/Traindata/TraindataRevise', data).then(res => {
          this.handelResponse(res, data => {
            _g.toastMsg('success', res.data)
            setTimeout(() => {
              this.editInfo = false
              this.GetTableData()
            }, 1000)
          })
        })
      }
    },
    print(row) {
      // console.log(row)
      window.open('http://8.142.34.26:8097/php/uploads/html/train.html?item=' +
          row.id)
    },
    // 删除培训信息
    confirmDelete(item) {
      this.$confirm('确认删除该培训信息？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          let data = {
            id: item.id
          }
          this.apiPost('admin/Traindata/TraindataDelete', data).then(res => {
            this.handelResponse(res, data => {
              // console.log(res)
              _g.toastMsg('success', res.data)
              this.GetTableData()
            })
          })
        })
        .catch(() => {
          // handle error
        })
    },
    // 查询培训信息
    Search() {
      if (this.time == null) {
        this.time = ['', '']
        console.log('this.time为空重置了')
      }
      let data = {
        // company: Lockr.get('schInfo')['sch_id_' + this.searchData.company]['sch_name'] ,
        company: this.searchData.company,
        traindata_name: this.searchData.traindata_name,
        start_time: this.time[0],
        end_time: this.time[1],
        issue: this.searchData.issue
      }
      // console.log(data)
      this.GetTableData(data)
    },
    // 结束培训
    stopExe(item) {
      // console.log(item)
      this.$confirm('确认结束该条培训信息？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          let data = {
            id: item.id
          }
          this.apiPost('admin/Traindata/TraindataEduend', data).then(res => {
            this.handelResponse(res, data => {
              _g.toastMsg('success', res.data)
              this.GetTableData()
            })
          })
        })
        .catch(() => {
          // handle error
        })
    }
  },
  created() {
    _g.closeGlobalLoading()
    // 当为高校管理员的账号登陆的时候，只会显示培训信息list，并没有新增跟操作按钮
    if (this.userInfo.level === 2) {
      this.operating = false
    }
    this.GetTableData()
  },
  computed: {},
  components: {},
  mixins: [http]
}
</script>
<style scoped>
.box {
  position: relative;
  border-radius: 3px;
  background: #fff;
  border-top: 3px solid #d2d6de;
  margin-bottom: 20px;
  width: 100%;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);
  border-top-color: #3c8dbc;
}
.box-body {
  border-top-left-radius: 0;
  border-top-right-radius: 0;
  border-bottom-right-radius: 3px;
  border-bottom-left-radius: 3px;
  padding: 10px;
  min-height: 0.01%;
  overflow-x: auto;
}
.box-header {
  height: 34px;
  line-height: 34px;
  color: #444;
  display: block;
  padding: 10px;
  position: relative;
}
.button-group {
  margin-left: 13px;
}
.pull-left {
  float: left;
}
.pull-right {
  float: right;
  /*margin-right: 50px;*/
}
.box-title {
  font-weight: 700;
  letter-spacing: 3px;
  display: inline-block;
  font-size: 18px;
  margin: 0;
}
.header-button {
  background-color: #3c8dbc;
  border-color: #367fa9;
}
.table-header {
  font-weight: bold;
}
.el-button--small {
  padding: 7px 9px;
}
.el-table .showwarn {
  background: oldlace;
}
.edit-btn {
  /*background: #367fa9;*/
  width: 60px;
  height: 28px;
}
.add-btn {
  background: #367fa9;
  margin: 0 10px;
}
.add-btn:hover {
  /* background: #367fa9; */
  background: #367fa9;
}
/*  .btn-link-large {
    padding: 13px 12px;
    font-size: 14px;
}*/
/* 选中某行时的背景色*/
.el-table__body tr.current-row > td {
  background-color: #92cbf1 !important;
}

/*鼠标移入某行时的背景色*/
.el-table--enable-row-hover .el-table__body tr:hover > td {
  background-color: #92cbf1;
}
</style>
